package me.ratel.demo.eBook.application.impl;

import me.ratel.demo.eBook.application.IUserService;
import me.ratel.demo.eBook.domain.model.user.IUserDao;
import me.ratel.demo.eBook.domain.model.user.User;
import me.ratel.demo.wechat.WeChat;
import me.ratel.demo.wechat.WeChatService;
import me.ratel.demo.wechat.entities.SnsOAuth2AccessTokenResponse;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ${user}
 * @time 2016/6/13 8:11
 */
@Service
public class UserService implements IUserService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired private IUserDao userDao;

    @Override public User get(Integer id) {
        return userDao.get(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override public Integer authorizeOAuth2User(String code, String state) {
        WeChatService weChatService = WeChat.newWeChat(
                "wx08379b83fa805962",
                "4d0c055d9d7256bc49131bec149acc24",
                "1357882102",
                "3520fc5282a8fd12ee4f4c1cae7d7e1e"
        );
        SnsOAuth2AccessTokenResponse snsOAuth2AccessTokenResponse = weChatService.snsOAuth2AccessToken(code);

        Integer userId;
        {
            Map<String, Object> condition = new HashMap<>();
            condition.put("openId", snsOAuth2AccessTokenResponse.getOpenId());
            List<User> users =  userDao.list(condition, null);
            userId = CollectionUtils.isEmpty(users)? null: users.get(0).getId();
        }
        return userId!=null? userId: userDao.save(new User("", snsOAuth2AccessTokenResponse.getOpenId()));
    }
}
